package com.antd.gateway.filter;

import cn.hutool.core.util.StrUtil;
import com.antd.common.core.constant.AntdConstant;
import com.antd.common.core.exception.BaseException;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;

/**
 * TODO
 *
 * @author 子丶沫
 * @version 1.0
 * @date 2020/11/19 17:47
 */
@Slf4j
@Component
@AllArgsConstructor
public class ImageCodeFilter extends AbstractGatewayFilterFactory {
    private final StringRedisTemplate redisTemplate;
    @Override
    public GatewayFilter apply(Object config) {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            // 不是登录请求，直接向下执行
            if (!StrUtil.containsAnyIgnoreCase(request.getURI().getPath(), AntdConstant.OAUTH_TOKEN_URL)) {
                return chain.filter(exchange);
            }
            // 验证流程
            validateCode(request);
            return chain.filter(exchange);
        };
    }
    private void  validateCode(ServerHttpRequest request){
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        String t = queryParams.getFirst("t");
        String code = queryParams.getFirst("code");
        if(StrUtil.isBlank(code)){
            throw new BaseException("验证码不能为空");
        }
        String oldCode = redisTemplate.opsForValue().get(AntdConstant.IMAGE_KEY + t);
        if(StrUtil.isBlank(oldCode)){
            throw new BaseException("验证码已失效");
        }
        if(!StrUtil.equalsIgnoreCase(code,oldCode)){
            throw new BaseException("验证码错误");
        }
        redisTemplate.delete(AntdConstant.IMAGE_KEY + t);
    }
}
